var Hello = {
    connection: null,
    startTime: null,
    log: function(msg) {
	$("#log").append("<p>" + msg + "</p>");
    },
    sendPing: function(to) {
	var ping = $iq({
	    to: to,
	    type: "get",
	    id: "ping1"
	}).c("ping", {xmlns: "urn:xmpp:ping"});
	Hello.log("Sending ping to " + to + ".");
	Hello.startTime = (new Date()).getTime();
	Hello.connection.send(ping);
    },
    handlePong: function(iq) {
	var elapsed = (new Date()).getTime() - Hello.startTime;
	Hello.log("Received pong from server in " + elapsed + " ms.");
	Hello.connection.disconnect();
	return false;
    }
};

$(document).ready(function() {
    $("#login_dialog").dialog({
        autoOpen: true,
	draggable: false,
	modal: true,
	title: "Connect to XMPP",
	buttons: {
	    "Connect": function() {
		$(document).trigger('connect', {
		    server: $("#server").val(),
		    jid: $('#jid').val(),
		    password: $('#password').val()
		});

		$('#password').val('');
		$(this).dialog('close');
	    }
	}
    });
});

$(document).bind('connect', function(ev, data) {
    var conn = new Strophe.Connection(data.server);
    conn.connect(data.jid, data.password, response); 
    Hello.connection = conn;
});

function response(status) {
    if (status === Strophe.Status.CONNECTED) {
        $(document).trigger('connected');
    } else if (status === Strophe.Status.DISCONNECTED) {
	$(document).trigger('disconnected');
    } else if (status === Strophe.Status.CONNECTING) {
        $(document).trigger('connecting');
    }
}

$(document).bind('connected', function() { 
    Hello.log("Connection established."); 
    Hello.connection.addHandler(Hello.handlePong, null, "iq", null, "ping1");
    
    var domain = Strophe.getDomainFromJid(Hello.connection.jid);
    Hello.sendPing(domain);
});

$(document).bind('connecting', function() { Hello.log("Connecting..."); });

$(document).bind('disconnected', function() { 
    Hello.log("Connection terminated."); 
    Hello.connection = null;
});
